﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Collections;

namespace ContentMigrator
{
    public partial class frmLoadMetabase : Form
    {
        public frmLoadMetabase()
        {
            InitializeComponent();
        }
        public frmLoadMetabase(string filename)
        {
            InitializeComponent();
            lblFile.Text = filename;
            XMLToDataGridView(filename, dataGridView1);
            BindColumnCombo();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            fd.Filter = "XML Files|*.xml";
            fd.ShowDialog();

            lblFile.Text = fd.FileName;
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            try
            {
                if (lblFile.Text.Trim() != string.Empty)
                {
                    XMLToDataGridView(lblFile.Text, dataGridView1);
                    BindColumnCombo();
                }
                else
                {
                    MessageBox.Show("Please select a metabase file", "LOAD", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                
                MessageBox.Show(ex.Message,"ERROR",  MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void XMLToDataGridView(string xmlfile, DataGridView dgv)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(xmlfile);
                XmlNodeList items = doc.SelectNodes("Data/Item");
                
                //add columns to grid
                XmlNode firstitem = items[0];
                if (firstitem == null)
                    return;

                dgv.Rows.Clear();
                if (dgv.Columns.Count == 0)
                    foreach (XmlAttribute attrib in firstitem.Attributes)
                    {
                        DataGridViewColumn col = new DataGridViewTextBoxColumn();
                        col.HeaderText = attrib.Name;
                        col.Name = attrib.Name;
                        dgv.Columns.Add(col);
                    }

                foreach (XmlNode item in items)
                {
                    int newrow = dgv.Rows.Add();
                    DataGridViewRow row = dgv.Rows[newrow];
                    foreach (XmlAttribute myattrib in item.Attributes) {
                        row.Cells[myattrib.Name].Value = myattrib.Value;
                    }
                }
            }
            catch (Exception ex)
            {
                
                throw new Exception("XMLToDataGridView: " + ex.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Add();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                DataViewGridToXML(lblFile.Text);
                MessageBox.Show("Save was successeful.", "SAVE", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, "SAVE ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void DataViewGridToXML(string dbfile)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                XmlNode data = doc.CreateNode(XmlNodeType.Element, "Data", string.Empty);

                foreach (DataGridViewRow myrow in dataGridView1.Rows)
                {
                    if (!myrow.IsNewRow)
                    {
                        XmlNode item = doc.CreateNode(XmlNodeType.Element, "Item", string.Empty);
                        foreach (DataGridViewColumn col in dataGridView1.Columns)
                        {
                            string val = string.Empty;
                            if (myrow.Cells[col.Name].Value != null)
                                val = (string)myrow.Cells[col.Name].Value.ToString();

                            item.Attributes.Append(doc.CreateAttribute(col.Name)).InnerText = val;
                        }

                        data.AppendChild(item);
                    }
                }
                doc.AppendChild(data);

                string outfile = dbfile.Replace(dbfile.Substring(dbfile.LastIndexOf(".")), ".xml");
                if (File.Exists(outfile))
                    File.Delete(outfile);
                doc.Save(outfile);
            }
            catch (Exception ex)
            {

                throw new Exception("DataViewGridToXML: " + ex.Message);
            }
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtFind.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("Please enter text to search for", "FIND", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                DataGridViewCell cell = FindText(txtFind.Text,cmbLookIn.Text);

                if (cell != null)
                {
                    dataGridView1.CurrentCell = cell;
                    cell.Selected = true;
                    btnReplace.Enabled = true;
                    btnReplaceAll.Enabled = true;
                }
                else
                {
                    MessageBox.Show("Text not found.", "FIND", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); 
            }
        }

        private void BindColumnCombo()
        {
            try
            {
                cmbLookIn.Items.Clear();

                if (dataGridView1.Rows.Count > 0)
                {
                    cmbLookIn.Items.Add("All columns");

                    foreach (DataGridViewColumn col in dataGridView1.Columns)
                    {
                        cmbLookIn.Items.Add(col.Name);
                    }
                    cmbLookIn.SelectedIndex = 0;
                }

            }
            catch (Exception ex)
            {
                
                throw new Exception("BindColumnCombo: " + ex.Message);
            }
        }

        private DataGridViewCell FindText(string text, string colname)
        {
            try
            {
                int startrow;
                int startcol;
                bool found = false;
                DataGridViewCell cell = null;
                if (dataGridView1.CurrentCell != null)
                {
                    
                    startrow = dataGridView1.CurrentCell.OwningRow.Index;
                    startcol = dataGridView1.CurrentCell.OwningColumn.Index;

                    if (startrow == dataGridView1.Rows.Count - 1 && startcol == dataGridView1.Columns.Count - 1)
                    {
                        switch (MessageBox.Show("Search as reached the end of the data. Would you like to start from the beginning?", "FIND", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                        {
                            case DialogResult.Yes:
                                startrow = 0;
                                startcol = 0;
                                dataGridView1.CurrentCell = dataGridView1.Rows[startcol].Cells[startcol];
                                break;
                            case DialogResult.No:
                                goto exit_routine;
                        }
                    }

                    for (int rowidx = startrow; rowidx < dataGridView1.Rows.Count; rowidx++)
                    {
                        if (colname == "All columns")
                            for (int colidx = startcol; colidx < dataGridView1.Columns.Count; colidx++)
                            {
                                cell = dataGridView1.Rows[rowidx].Cells[colidx];
                                object val = cell.Value;
                                if (val != null)
                                    if (val.ToString().Contains(text) && cell != dataGridView1.CurrentCell)
                                    {
                                        found = true;
                                        goto exit_routine;
                                    }
                                    else
                                        cell = null;
                            }
                        else
                        {
                            cell = dataGridView1.Rows[rowidx].Cells[colname];
                            object val = cell.Value;
                            if (val != null)
                                if (val.ToString().Contains(text) && cell != dataGridView1.CurrentCell)
                                {
                                    found = true;
                                    goto exit_routine;
                                }
                                else
                                    cell = null;
                        }
                    }
                exit_routine:
                    if (found == true)
                        return cell;
                    else
                        return null;
                }
                else
                   return null;
            }
            catch (Exception ex)        
            {
                
                throw new Exception("FindText: " + ex.Message);
            }
        }

        private ArrayList FindTextAll(string text, string colname)
        {
            try
            {
                int startrow;
                int startcol;
                DataGridViewCell cell = null;
                ArrayList ret = new ArrayList();

                startrow = dataGridView1.CurrentCell.OwningRow.Index;
                startcol = dataGridView1.CurrentCell.OwningColumn.Index;

                if (startrow == dataGridView1.Rows.Count - 1 && startcol == dataGridView1.Columns.Count - 1)
                {
                    switch (MessageBox.Show("Search as reached the end of the data. Would you like to start from the beginning?", "FIND", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                    {
                        case DialogResult.Yes:
                            startrow = 0;
                            startcol = 0;
                            dataGridView1.CurrentCell = dataGridView1.Rows[startcol].Cells[startcol];
                            break;
                        case DialogResult.No:
                            goto exit_routine;
                    }
                }

                for (int rowidx = startrow; rowidx < dataGridView1.Rows.Count; rowidx++)
                {
                    if (colname == "All columns")
                        for (int colidx = startcol; colidx < dataGridView1.Columns.Count; colidx++)
                        {
                            cell = dataGridView1.Rows[rowidx].Cells[colidx];
                            object val = cell.Value;
                            if (val != null)
                                if (val.ToString().Contains(text) && cell != dataGridView1.CurrentCell)
                                {
                                    ret.Add(cell);
                                }
                        }
                    else
                    {
                        cell = dataGridView1.Rows[rowidx].Cells[colname];
                        object val = cell.Value;
                        if (val != null)
                            if (val.ToString().Contains(text) && cell != dataGridView1.CurrentCell)
                            {
                                ret.Add(cell);
                            }
                    }
                }
                exit_routine:
                return ret;
            }
            catch (Exception ex)
            {

                throw new Exception("FindText: " + ex.Message);
            }
        }

        private void btnReplace_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtFind.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("Please enter replacement text", "FIND", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (dataGridView1.CurrentCell != null) {
                    object val = dataGridView1.CurrentCell.Value;
                    if (val != null)
                    {
                        dataGridView1.CurrentCell.Value = val.ToString().Replace(txtFind.Text, txtReplace.Text);
                    }
                }
            }
            catch (Exception ex)
            {
               
                MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); 
            }
        }

        private void btnReplaceAll_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtFind.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("Please enter replacement text", "FIND", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                //start at beginning
                DataGridViewCell currentcell = dataGridView1.Rows[0].Cells[0];
                currentcell.Selected = true;
                dataGridView1.CurrentCell = currentcell;

                ArrayList cells = FindTextAll(txtFind.Text,cmbLookIn.Text);

                foreach (DataGridViewCell cell in cells)
                {
                    object val = cell.Value;
                    if (val != null)
                    {
                        cell.Value = val.ToString().Replace(txtFind.Text, txtReplace.Text);
                    }
                }

                if (cells.Count > 0)
                    MessageBox.Show("All instances were replaced", "REPLACE ALL", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                
                MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
